<template>
	<a-modal
		v-model:open="visible"
		title="查看JSON"
		:width="800"
		:mask-closable="false"
		:destroy-on-close="true"
		@cancel="onClose"
	>
		<XnHighlightjs :code="jsonData" autodetect />
		<template #footer>
			<a-button type="primary" @click="handleCopy">复制</a-button>
			<a-button type="primary" ghost @click="onClose">取消</a-button>
		</template>
	</a-modal>
</template>

<script setup>
	import { message } from 'ant-design-vue'
	const visible = ref(false)
	const jsonData = ref('')

	// 打开弹窗
	const onOpen = (jsonStr) => {
		visible.value = true
		const code = JSON.parse(jsonStr)
		jsonData.value = JSON.stringify(code, undefined, 2)
	}
	// 关闭弹窗
	const onClose = () => {
		visible.value = false
		jsonData.value = ''
	}
	// 复制
	const handleCopy = () => {
		copyTextToClipboard(jsonData.value).then(() => {
			message.success('复制成功')
		})
	}
	const copyTextToClipboard = async (text) => {
		try {
			await navigator.clipboard.writeText(text)
		} catch (err) {
			message.warning('复制失败')
		}
	}
	defineExpose({
		onOpen
	})
</script>
